package com.example.houselease.config;

import com.alibaba.fastjson.JSON;
import com.example.houselease.filter.JwtAuthorizationFilter;
import com.example.houselease.web.JsonResult;
import com.example.houselease.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * spring security 配置类
 * EnableGlobalMethodSecurity：开启‘基于方法的权限检查’
 *
 * @author xf
 * @version 0.0.1
 * */
@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    /**
     * Spring会自动调用此方法，
     * 得到`AuthenticationManager`类型的对象，
     * 并保存在Spring容器中
     * */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 返回密码加密对象
     * */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置认证、访问相关配置
     * */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 处理“需要通过认证，但是实际上未通过认证就发起的请求”导致的错误
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                String message = "未检测到登录，请登录！（在开发阶段，看到此提示时，请检查客户端是否携带了JWT向服务器端发起请求）";
                JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);
                response.setContentType("application/json; charset=utf-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.println(JSON.toJSONString(jsonResult));
                printWriter.close();
            }
        });

        // 白名单
        String[] urls = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/admins/login",
                "/image/**",
                "/static/avatar/**"
        };

        http.cors();// 解决跨域问题

        // 配置URL的访问控制
        http.authorizeRequests() // 配置URL的访问控制
                .mvcMatchers(urls) // 匹配某些URL
                .permitAll() // 直接许可，即：不需要通过认证就可以直接访问
                .anyRequest() .authenticated() // 其他任何请求 需要通过认证
                .and()
                .addFilterBefore(jwtAuthorizationFilter,
                        UsernamePasswordAuthenticationFilter.class) //添加过滤器
                .csrf().disable(); //允许post请求。  禁用“防止伪造的跨域攻击”这种防御机制

        // 调用formLogin()表示启用登录表单页和登出页，如果未调用此方法，则没有登录表单页和登出页
//        http.formLogin();
    }

}